﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TCP多网口操作Demo
{
    public partial class Form1 : UIForm
    {
        public Form1()
        {
            InitializeComponent();

            clear.FillColor = Color.Maroon;
        }
        TcpClient tcpClient1;
        TcpClient tcpClient2;

        int id1, id2;

        string tcpReceiveData1;
        string tcpReceiveData2;
        private void initialize_Click(object sender, EventArgs t)
        {
            initialize.Enabled = false;


            tcpClient1 = new TcpClient();
            tcpClient1.Connecting = (client, e) =>
            {
            };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
            tcpClient1.Connected = (client, e) =>
            {
                Status1.FillColor = Color.Green;
                Console.WriteLine(client.IP);

                //连接发送的数据
                byte[] t1Data = Encoding.UTF8.GetBytes("/idn?");
                tcpClient1.Send(t1Data);
            };//成功连接到服务器
            tcpClient1.Disconnecting = (client, e) => { Console.WriteLine(client.IP); };//即将从服务器断开连接。此处仅主动断开才有效。
            tcpClient1.Disconnected = (client, e) => { Console.WriteLine(client.IP); };//从服务器断开连接，当连接不成功时不会触发。
            tcpClient1.Received = (client, e, r) =>
            {
                var mes = Encoding.UTF8.GetString(e.Buffer, 0, e.Len);
                tcpClient1.Logger.Info($"客户端接收到信息：{mes}");
                Console.WriteLine(mes);

                tcpClient2.Send(mes);


            };

            //载入配置
            tcpClient1.Setup(new TouchSocketConfig()
                .SetRemoteIPHost(new IPHost($"{ip1.Text}:{port1.Text}"))
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();//添加一个日志注入
                }));

            tcpClient1.Connect();//调用连接，当连接不成功时，会抛出异常。

            tcpClient1.Logger.Info("1客户端成功连接");


            //---------------------------------------------------------------------


            tcpClient2 = new TcpClient();
            tcpClient2.Connecting = (client, e) => { };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
            tcpClient2.Connected = (client, e) =>
            {
                Status2.FillColor = Color.Green;
                Console.WriteLine(client.IP);

                //连接发送的数据
                byte[] t2Data = Encoding.UTF8.GetBytes("/idn?");
                tcpClient2.Send(t2Data);
            };//成功连接到服务器
            tcpClient2.Disconnecting = (client, e) => { Console.WriteLine(client.IP); };//即将从服务器断开连接。此处仅主动断开才有效。
            tcpClient2.Disconnected = (client, e) => { Console.WriteLine(client.IP); };//从服务器断开连接，当连接不成功时不会触发。
            tcpClient2.Received = (client, e, r) =>
            {
                var mes = Encoding.UTF8.GetString(e.Buffer, 0, e.Len);
                tcpClient2.Logger.Info($"客户端接收到信息：{mes}");
                Console.WriteLine(mes);

                //数据记录
                uiDataGridView1.Invoke(new Action(() =>
                {
                    uiDataGridView1.Rows.Add(++id1,100, 200);

                    uiDataGridView1.Rows[uiDataGridView1.Rows.Count - 1].Cells[3].Value = 300;
                }));
               

            };

            //载入配置
            tcpClient2.Setup(new TouchSocketConfig()
                .SetRemoteIPHost(new IPHost($"{ip2.Text}:{port2.Text}"))
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();//添加一个日志注入
                }));

            tcpClient2.Connect();//调用连接，当连接不成功时，会抛出异常。


            tcpClient2.Logger.Info("2客户端成功连接");

        }

        private void save1_Click(object sender, EventArgs e)
        {
            List<DataGridModel.DataGridViewModel_1> data1 = new List<DataGridModel.DataGridViewModel_1>();
            List<DataGridModel.DataGridViewModel_2> data2 = new List<DataGridModel.DataGridViewModel_2>();
            //将datagrid1的数据整合保存到datagrid2
            foreach (DataGridViewRow row in uiDataGridView1.Rows)
            {
                data1.Add(new DataGridModel.DataGridViewModel_1()
                {
                    A = float.Parse(row.Cells[1].Value.ToString()),
                    B = float.Parse(row.Cells[2].Value.ToString()),
                    C = float.Parse(row.Cells[3].Value.ToString()),
                });
            }
            //对data1进行计算
            data2= data1.GroupBy(x=>x.A).Select(x =>
            {
                //计算的位置
                return new DataGridModel.DataGridViewModel_2() { A = x.Key, C = x.Average(z=>z.C) };
            }).ToList();

            //给datagridview2赋值
            foreach (var item in data2)
            {
                uiDataGridView2.Rows.Add(++id2,item.A,item.C);
            }
        }

        private void clear_Click(object sender, EventArgs e)
        {
            id2 = 0;
            uiDataGridView2.Rows.Clear();
        }

        private async void measure_Click(object sender, EventArgs e)
        {
            if (tcpClient1 is null || tcpClient2 is null)
            {
                MessageBox.Show("请连接后发送");
                return;
            }
            int count = int.Parse(numreading.Text);
            int delayMs = int.Parse(delay.Text);


            do
            {
                for (int i = 0; i < count; i++)
                {
                    byte[] t1Data = Encoding.UTF8.GetBytes($"{aText.Text}{bText.Text}");
                    tcpClient1.Send(t1Data);
                    await Task.Delay(delayMs);

                }
            } while (uiCheckBox1.Checked);

            MessageBox.Show("运行结束");
        }
    }
}
